package com.weatherstation.security;

import com.weatherstation.entity.RolePermission;
import com.weatherstation.mapper.RolePermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionService {

    private final RolePermissionMapper rolePermissionMapper;

    @Autowired
    public PermissionService(RolePermissionMapper rolePermissionMapper) {
        this.rolePermissionMapper = rolePermissionMapper;
    }

    /**
     * 根据角色代码获取权限列表
     * @param roleCode 角色代码
     * @return 权限集合
     */
    public Collection<GrantedAuthority> getAuthorities(String roleCode) {
        // 添加ROLE_前缀作为角色权限
        List<GrantedAuthority> authorities = List.of(new SimpleGrantedAuthority("ROLE_" + roleCode.toUpperCase()));
        
        // 获取该角色的所有权限
        List<RolePermission> permissions = rolePermissionMapper.findByRoleCode(roleCode);
        
        // 将权限转换为GrantedAuthority对象
        List<GrantedAuthority> permissionAuthorities = permissions.stream()
                .map(rp -> new SimpleGrantedAuthority(rp.getPermissionCode()))
                .collect(Collectors.toList());
        
        // 合并角色和权限
        authorities = new java.util.ArrayList<>(authorities);
        authorities.addAll(permissionAuthorities);
        
        return authorities;
    }
    
    /**
     * 检查用户是否有指定的权限
     * @param roleCode 角色代码
     * @param permissionCode 权限代码
     * @return 是否有权限
     */
    public boolean hasPermission(String roleCode, String permissionCode) {
        List<RolePermission> permissions = rolePermissionMapper.findByRoleCode(roleCode);
        return permissions.stream()
                .anyMatch(rp -> rp.getPermissionCode().equals(permissionCode));
    }
} 